<script setup>
import { ref } from 'vue'
import ChannelSelect from '@/views/article/components/ChannelSelect.vue'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { artGetArticleService, artPublishService, artSaveArticleService } from '@/api/article.js'
import { ElMessage } from 'element-plus'
import { baseURL } from '@/utils/request.js'
// 引入axios
import axios from 'axios'

const drawerVisible = ref(false)
const emit = defineEmits(['updateArticle'])
const confirmClick = async (state) => {
  console.log('confirmClick')
  formModel.value.state = state
  //   需要将formModel.value转换为formData数据
  const fd = new FormData()
  for (let key in formModel.value) {
    fd.append(key, formModel.value[key])
  }
  if (formModel.value.id) {
    await artSaveArticleService(fd)
    drawerVisible.value = false
    emit('updateArticle')
    ElMessage.success('修改文章成功')
  } else {
    await artPublishService(fd)
    drawerVisible.value = false
    emit('updateArticle', 'add')
    ElMessage.success('新增文章成功')
  }
}
const title = ref('')
const editorRef = ref()
const open = async (data) => {
  console.log(data)
  drawerVisible.value = true
  if (data.id) {
    title.value = '修改文章'
    let response = await artGetArticleService(data.id)
    formModel.value = { ...response.data.data }
    // 图片回显需要单独处理为网络图片
    imgUrl.value = baseURL + formModel.value.cover_img
    //   然后在把表单数据的img转换为file格式
    const file = await fetchImageAsFile(imgUrl.value, formModel.value.cover_img)
    console.log(file)
    formModel.value.cover_img = file
  } else {
    title.value = '新增文章'
    // 清空表单数据
    formModel.value.title = ''
    formModel.value.cate_id = ''
    imgUrl.value = ''
    // 清空编辑器数据
    formModel.value.content = ''
  }
}
// 获取网络图片并转换为File对象的函数
async function fetchImageAsFile(url, filename) {
  try {
    // 发送GET请求获取图片的二进制数据
    const response = await axios({
      url,
      method: 'GET',
      responseType: 'arraybuffer' // 设置响应类型为arraybuffer以接收二进制数据
    })

    // 创建Blob对象
    const blob = new Blob([response.data], { type: response.headers['content-type'] }) // 假设图片为png格式，根据实际情况调整type

    // 创建File对象
    const file = new File([blob], filename, { type: response.headers['content-type'] })

    // 返回File对象
    return file
  } catch (error) {
    console.error('An error occurred while fetching the image:', error)
    return null
  }
}
defineExpose({
  open
})

// 表单数据
const formModel = ref({
  title: '',
  cate_id: '',
  cover_img: '', //基于file
  content: '',
  state: ''
})
const updateChannel = (val) => (formModel.value.cate_id = val)

const imgUrl = ref('')
const onImageUpload = (uploadFile) => {
  console.log(uploadFile)
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  formModel.value.cover_img = uploadFile.raw
}
</script>

<template>
  <el-drawer v-model="drawerVisible" size="50%">
    <template #header>
      <h4>{{ title }}</h4>
    </template>
    <template #default>
      <el-form :model="formModel">
        <el-form-item
          label="文章标题"
          prop="title"
          :rules="{ required: true, message: '请输入文章标题', trigger: 'blur' }"
        >
          <el-input v-model="formModel.title" />
        </el-form-item>
        <el-form-item
          label="文章分类"
          prop="cate_id"
          :rules="{ required: true, message: '请选择文章分类', trigger: 'blur' }"
        >
          <template #default>
            <ChannelSelect
              v-model="formModel.cate_id"
              @update:modelValue="updateChannel"
              width="100%"
            />
          </template>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="onImageUpload"
          >
            <el-image v-if="imgUrl" :src="imgUrl" class="avatar" lazy />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="文章内容"
          prop="content"
          :rules="[{ required: true, message: '请输入文章内容', trigger: 'blur' }]"
        >
          <div class="editor">
            <quillEditor
              ref="editorRef"
              v-model:content="formModel.content"
              content-type="html"
              theme="snow"
            ></quillEditor>
          </div>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto; justify-content: flex-start; display: flex">
        <el-button @click="confirmClick('草稿')">草稿</el-button>
        <el-button type="primary" @click="confirmClick('已发布')">发布</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.editor {
  width: 100%;
  height: 350px;
}
</style>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
